import numpy as np
import matplotlib.pyplot as plt
import os
import sys

# 获取当前脚本的完整路径
script_path = os.path.abspath(sys.argv[0])
# 从完整路径中获取目录
script_dir = os.path.dirname(script_path)
# 从完整路径中分离出文件名
script_name = os.path.basename(script_path)
# 使用 splitext() 函数分离文件名和扩展名
script_name_without_extension, _ = os.path.splitext(script_name)

# 创建保存图像的完整路径
save_path = os.path.join(script_dir, script_name_without_extension + ".png")

def draw_cum_prob_curve(data,bins=20,title='Distribution Of Errors',xlabel='The Error(mm)',pic_path=''):
    """
    plot Probability distribution histogram and Cumulative probability curve.
    
    > @param[in] data:          The error data
    > @param[in] bins:          The number of hist
    > @param[in] title:         The titile of the figure
    > @param[in] xlabel:        The xlable name
    > @param[in] pic_path:      The path where you want to save the figure
    return:     void
    """
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    from matplotlib.ticker import FuncFormatter
    from matplotlib.pyplot import MultipleLocator
    def to_percent(temp,position=0):          # convert float number to percent
        return '%1.0f'%(100*temp) + '%'
    fig, ax1 = plt.subplots(1, 1, figsize=(12, 6), dpi=100, facecolor='w')
    font1 = {'weight': 600, 'size': 15}
    
    n, bins, patches=ax1.hist(data,bins =bins, alpha = 0.65,edgecolor='k') # Probability distribution histogram
    yt=plt.yticks()
    yt1=yt[0].tolist()
    yt2=[i/sum(n) for i in yt1]
    ytk1=[to_percent(i) for i in yt2 ]
    plt.yticks(yt1,ytk1)
    X=bins[0:-1]+(bins[1]-bins[0])/2.0 
    bins=bins.tolist()
    freq=[f/sum(n) for f in n]
    acc_freq=[]
    for i in range(0,len(freq)):
        if i==0:
            temp=freq[0]
        else:
            temp=sum(freq[:i+1])
        acc_freq.append(temp)
    ax2=ax1.twinx()                         # double ylable
    ax2.plot(X,acc_freq)                    # Cumulative probability curve
    ax2.yaxis.set_major_formatter(FuncFormatter(to_percent))
    ax1.set_xlabel(xlabel,font1)
    ax1.set_title(title,font1)
    ax1.set_ylabel('Frequency',font1)
    ax2.set_ylabel("Cumulative Frequency",font1)
    #plt.savefig(pic_path,format='png', dpi=300)

example_list=[]
n=10000
for i in range(n):
    tmp=[np.random.normal()]
    example_list.extend(tmp)
tit='TEST'
xla='DATA'
draw_cum_prob_curve(example_list,50,tit,xla)
plt.savefig(save_path, dpi=300)
plt.show()
